package com.sxjh.controller.ny;


import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.sxjh.annotation.UserLog;
import com.sxjh.common.BaseController;
import com.sxjh.common.Constant;
import com.sxjh.common.Result;
import com.sxjh.common.ZPage;
import com.sxjh.entity.*;
import com.sxjh.entity.param.*;
import com.sxjh.entity.result.GoodsLocationList2Result;
import com.sxjh.entity.result.GoodsLocationLoadResult;
import com.sxjh.service.GoodsLocationService;
import com.sxjh.service.MateriaLoadService;
import com.sxjh.service.MateriaUnloadService;
import com.sxjh.service.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 货物地点  前端控制器
 * 权限配置
 * </p>
 *
 * @author zixin
 * @since 2021-06-05
 */
@Api(tags = "货物地点")
@RestController
@RequestMapping("/goods-location")
public class GoodsLocationController extends BaseController {

    @Autowired
    private GoodsLocationService goodsLocationService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private MateriaLoadService materiaLoadService;

    @Autowired
    private MateriaUnloadService materiaUnloadService;


    @ApiOperation("列表")
    @GetMapping
    //@Authorization("goods-location.list")
    @ApiOperationSupport(author = "权限：goods-location.list")
    Result<ZPage<GoodsLocationListParam>> list(GoodsLocationListParam param) {
        IPage iPage = new Page(param.getCurrent(), param.getSize());
        if (param.getSize() == -1) {
            iPage.setSize(Constant.maxSize);
        }
        iPage = goodsLocationService.queryPage(iPage, param);
        ZPage<GoodsLocationListParam> zPage = copyPage(iPage, GoodsLocationListParam::new);
        return Result.ok(zPage);
    }

    @ApiOperation("计划单列表所属工厂查询")
    @GetMapping("factory-list")
    Result<ZPage<FactoryEntity>> list2(GoodsLocationFactoryParam param) {
        if (param != null) {
            String type = param.getType();
            boolean b = StringUtils.isNotBlank(type);
            if (b && "Down".equals(type)) {
                param.setType("1");
            } else if (b && "Up".equals(type)) {
                param.setType("0");
            }
        }
        IPage iPage = new Page(param.getCurrent(), param.getSize());
        if (param.getSize() == -1) {
            iPage.setSize(Constant.maxSize);
        }
        iPage = goodsLocationService.queryPage2(iPage, param);
        ZPage<FactoryEntity> zPage = copyPage(iPage, FactoryEntity::new);
        return Result.ok(zPage);
    }

    @ApiOperation("货物下拉框")
    @GetMapping("/select")
    Result<List<GoodsLocationList2Result>> select() {
        List<GoodsLocation> list = goodsLocationService.list(
                new LambdaQueryWrapper<GoodsLocation>()
                        .select(GoodsLocation::getId, GoodsLocation::getName, GoodsLocation::getType));
        List<GoodsLocationList2Result> results = copyList(list, GoodsLocationList2Result::new);
        return Result.ok(results);
    }

    @ApiOperation("与物料的关系列表")
    @GetMapping("/un-list")
//  @Authorization("goods-location.un-list")
    Result<List<GoodsLocationLoadResult>> unList(@Validated GoodsLocationUnListParam param) {
        List<GoodsLocationLoadResult> results = new ArrayList<>();
        if (param.getType() == 0) {
            // 装货点
            List<MateriaLoad> list = materiaLoadService.list(new LambdaQueryWrapper<MateriaLoad>().eq(MateriaLoad::getMaterialId, param.getMaterialId()));
            list.stream().forEach(materialLoad -> {
                GoodsLocationLoadResult goodsLocationLoadResult = new GoodsLocationLoadResult();
                goodsLocationLoadResult.setId(materialLoad.getLoadId());
                results.add(goodsLocationLoadResult);
            });
        }
        if (param.getType() == 1) {
            // 卸货点
            List<MateriaUnload> list = materiaUnloadService.list(new LambdaQueryWrapper<MateriaUnload>().eq(MateriaUnload::getMaterialId, param.getMaterialId()));
            list.stream().forEach(materialUnLoad -> {
                GoodsLocationLoadResult goodsLocationLoadResult = new GoodsLocationLoadResult();
                goodsLocationLoadResult.setId(materialUnLoad.getUnloadId());
                results.add(goodsLocationLoadResult);
            });
        }
        return Result.ok(results);
    }

    @ApiOperation("更新物料与货物绑定关系")
    @PostMapping("/bind/{materialId}")
    @ApiImplicitParam(name = "materialId", value = "物料ID")
    //@Authorization("goods-location.bind")
    @UserLog(desc = "内部倒运-更新物料与货物绑定关系", roleCode = "goods-location.bind")
    Result<Void> updateBind(@PathVariable Integer materialId, @RequestBody @Validated GoodsLocationUpdateBindParam param) {
        materiaLoadService.remove(new LambdaQueryWrapper<MateriaLoad>().eq(MateriaLoad::getMaterialId, materialId));
        if (param.getList() != null) {
            for (Integer id : param.getList()) {
                MateriaLoad materiaLoad = new MateriaLoad();
                materiaLoad.setMaterialId(materialId);
                materiaLoad.setLoadId(id);
                materiaLoadService.save(materiaLoad);
            }
        }
        materiaUnloadService.remove(new LambdaQueryWrapper<MateriaUnload>().eq(MateriaUnload::getMaterialId, materialId));
        if (param.getList2() != null) {
            for (Integer id : param.getList2()) {
                MateriaUnload materialLoad = new MateriaUnload();
                materialLoad.setMaterialId(materialId);
                materialLoad.setUnloadId(id);
                materiaUnloadService.save(materialLoad);
            }
        }
        return Result.ok();
    }

    /**
     * 增加货物地点
     */
    @ApiOperation("增加")
    @PostMapping
    //@Authorization("goods-location.add")
    @UserLog(desc = "内部倒运-添加装/卸货物地点", roleCode = "goods-location.add")
    Result<String> add(@RequestBody @Validated GoodsLocationAddParam param) {
        // if (param.getType() == 0)
        //   if (param.getIntervalTime() == null || param.getIntervalTime() < 1) return Result.err("装货地间隔时间必填");
        GoodsLocation entity = CglibUtil.copy(param, GoodsLocation.class);
        String record = String.format("地点类型：%s，地点名称：%s", "0".equals(param.getType()) ? "装货点" : "卸货点", param.getName());
        return goodsLocationService.save(entity) ? Result.ok(record) : Result.err("保存失败");
    }

    /**
     * 修改
     */
    @ApiOperation("修改")
    @PostMapping("/update")
    //@Authorization("goods-location.update")
    @UserLog(desc = "内部倒运-编辑装/卸货物地点", roleCode = "goods-location.update")
    Result<String> update(@RequestBody @Validated GoodsLocationUpdateParam param) {
        GoodsLocation entity = CglibUtil.copy(param, GoodsLocation.class);
        GoodsLocation goodsLocation = goodsLocationService.getById(param.getId());
        if (null == goodsLocation) {
            return err("参数有误，找不到记录");
        }
    /*if (goodsLocation.getType().intValue() == 0 && (param.getIntervalTime() == null || param.getIntervalTime() <=0)) {
      return err("间隔时间必须大于0");
    }*/
        String record = String.format("地点类型：%s，地点名称：%s", "0".equals(goodsLocation.getType()) ? "装货点" : "卸货点", param.getName());
        return goodsLocationService.updateById(entity) ? ok(record) : err("修改失败");
    }

    /**
     * 删除货物地点
     */
    @ApiOperation("删除")
    @GetMapping("/del/{id}")
    //@Authorization("goods-location.del")
    @UserLog(desc = "内部倒运-删除装/卸货物地点", roleCode = "goods-location.del")
    Result<String> del(@PathVariable Integer id) {
        int count = taskService.count(
                new LambdaQueryWrapper<Task>()
                        .eq(Task::getLoadId, id)
                        .or()
                        .eq(Task::getUnloadId, id));
        if (count > 0) return Result.err("请先删除货物点对应的任务");
        GoodsLocation goodsLocation = goodsLocationService.getById(id);
        if (null == goodsLocation) {
            return err("参数有误，找不到记录");
        }
        String record = String.format("地点类型：%s，地点名称：%s", "0".equals(goodsLocation.getType()) ? "装货点" : "卸货点", goodsLocation.getName());
        return goodsLocationService.removeById(id) ? Result.ok(record) : Result.err("删除失败，ID不存在或其他异常");
    }


    @ApiOperation("启用/禁用")
    @GetMapping(value = "/activate")
    @UserLog(desc = "内部倒运-修改车间", roleCode = "nbdy.workshop.update")
    public Result<Object> delete(@RequestParam("id") String id, @RequestParam("activateFlag") int activateFlag) {
        GoodsLocation params = new GoodsLocation();
        params.setId(Integer.valueOf(id));
        params.setActivateFlag(activateFlag);
        goodsLocationService.updateById(params);
        return Result.ok(HttpStatus.OK);
    }

}

